package com.guigu.health.controller;

import com.alibaba.fastjson.JSON;
import com.guigu.health.utils.ShiroUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName:BaseController
 * @Description:由于shiro在授权失败后,直接重定向到页面去,
 * 在axios中返回的是jsp,会报错,所有我们需要通过一个
 * BaseController 来统一处理，然后被其他 Controller 继承即可，
 * 对于JSON和页面跳转，我们只需要做一个Ajax判断处理即可。
 * @Author:longtao
 * @Date:2021/4/11
 * @Version:1.0
 */
public abstract class BaseController {
    /**
     * 权限异常
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        if (ShiroUtils.isAjaxRequest(request)) {
            // 输出JSON
            Map<String,Object> map = new HashMap<>();
            map.put("code", "-998");
            writeJson(map, response);
            return null;
        } else {
            return "redirect:/index.jsp";
        }
    }

    /**
     * 返回json
     * @param map
     * @param response
     */
    private void writeJson(Map<String,Object> map, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            out.write(JSON.toJSONString(map));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}
